using UnityEngine;

public class ShopItemButton : MonoBehaviour
{
	public UISprite displaySprite;

	public GameObject ownedLabel;

	public PriceTag priceTag;

	private StoreItemsConfig.StoreItem myItem;

	public void Init(StoreItemsConfig.StoreItem item)
	{
		myItem = item;
		UITools.ChangeSprite(displaySprite, item.previewSpriteName);
		UpdateButtonStatus();
	}

	private void UpdateButtonStatus()
	{
		bool flag = StoreItemsConfig.instance.IsStockpilable(myItem.type) || !PlayerInventory.instance.isOwned(myItem.name);
		priceTag.gameObject.SetActive(flag);
		ownedLabel.SetActive(!flag);
		if (flag)
		{
			priceTag.Init(myItem.cost, myItem.currency);
		}
	}

	public void ClickToBuyItem()
	{
		if (!StoreItemsConfig.instance.IsStockpilable(myItem.type) && PlayerInventory.instance.isOwned(myItem.name))
		{
			TableTennisDialog.instance.ShowOk("Already Owned", "You already own this item.", "Ok", null);
		}
		else if (!HasMoneyToBuyItem())
		{
			TableTennisDialog.instance.ShowNotEnoughCoins(myItem.cost);
		}
		else if (PlayerInventory.instance.isOwned(myItem.name))
		{
			int numberOfItemsOwned = PlayerInventory.instance.GetNumberOfItemsOwned(myItem.name);
			TableTennisDialog.instance.ShowYesNo("Already Owned", "You already own " + numberOfItemsOwned + " " + myItem.name + ((numberOfItemsOwned <= 1) ? string.Empty : "s") + ". (Dismiss using top corner cancel button)", "Buy more", "Use item", delegate(bool complete)
			{
				NavigationManager.instance.Pop();
				if (complete)
				{
					BuyItem();
				}
				else
				{
					StoreItemsConfig.instance.ApplyItem(myItem.name);
					PlayerInventory.instance.RemoveSingleItem(myItem.name);
					TableTennisDialog.instance.ShowOk("Congrats", "Congrats! You used a " + myItem.name, "Ok", null);
				}
			});
		}
		else
		{
			BuyItem();
		}
	}

	private bool HasMoneyToBuyItem()
	{
		int num = 0;
		if (myItem.currency == CurrencyType.coins)
		{
			num = GGPlayerSettings.instance.Model.coins;
		}
		else if (myItem.currency == CurrencyType.ggdollars)
		{
			num = GGPlayerSettings.instance.Model.giraffeDollars;
		}
		return myItem.cost <= num;
	}

	private void BuyItem()
	{
		SpendItemCost();
		ObtainItem();
		TableTennisDialog.instance.ShowOk("Congrats", "Congrats! You bought a " + myItem.name, "Ok", null);
	}

	private void SpendItemCost()
	{
		if (myItem.currency == CurrencyType.coins)
		{
			GGPlayerSettings.instance.walletManager.BuyItemCoins(myItem.cost);
		}
		else if (myItem.currency == CurrencyType.ggdollars)
		{
			GGPlayerSettings.instance.walletManager.BuyItemDollars(myItem.cost);
		}
	}

	private void ObtainItem()
	{
		PlayerInventory.instance.buyItem(myItem.name, StoreItemsConfig.instance.IsStockpilable(myItem.type));
		UpdateButtonStatus();
	}
}
